use actix_web::{web, HttpResponse, post};
use serde::{Deserialize, Serialize};
use jsonwebtoken::{encode, Header,  EncodingKey};
use crate::response::api_response::ApiResponse;

/// Our claims struct, it needs to derive `Serialize` and/or `Deserialize`
#[derive(Debug, Serialize, Deserialize)]
struct Claims {
    sub: String,
    exp: usize,
}

#[derive(Deserialize)]
struct LoginRequest {
    username: Option<String>,
    password: Option<String>,
}

#[post("/login")]
pub async fn login(req: web::Json<LoginRequest>) -> HttpResponse  {
    let username = req.username.clone().unwrap_or_default();
    let password = req.password.clone().unwrap_or_default();

    // 简单的用户名密码校验
    if username == "admin" && password == "admin" {
        let exp = 10000; // 过期时间（Unix 时间戳，示例为 10,000 秒后）
        let claims = Claims {
            sub: username.clone(),
            exp,
        };
        let token = encode(&Header::default(), &claims, &EncodingKey::from_secret("secret".as_ref())).unwrap();

        ApiResponse::success(token)
    } else {
        ApiResponse::<()>::fail(1, "Invalid credentials")
    }
}
